/*
 * @Author: your name
 * @Date: 2021-08-13 10:29:01
 * @Description: In User Settings Edit
 * @FilePath: /wx-weapp/utils/enhancer/core/dep.js
 */

/* @flow */

import { remove } from "../utils/observer";

let uid = 0;

/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
export default class Dep {
  static target;
  id;
  subs;

  constructor() {
    this.id = uid++;
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  removeSub(sub) {
    remove(this.subs, sub);
  }

  depend() {
    if (Dep.target) {
      Dep.target.addDep(this);
    }
  }

  notify() {
    const subs = this.subs.slice();
    subs.sort((a, b) => a.id - b.id);
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update();
    }
  }
}

// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
Dep.target = null;
let targetStack = [];
Dep.pushTarget = function pushTarget(target) {
    targetStack.push(target);
    Dep.target = target;
};
Dep.popTarget = function popTarget() {
    targetStack.pop();
    Dep.target = targetStack[targetStack.length - 1];
};
